package app.blog.entity;

import java.util.ArrayList;
import java.util.List;

import slap.berkeleydb.BDB;
import slap.paradigm.Function;

import app.blog.Blog;

import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
import com.sleepycat.persist.model.Relationship;
import com.sleepycat.persist.model.SecondaryKey;


@Entity
public class Tag {
	
	protected static PrimaryIndex<Integer, Tag> primaryIndex = 
		BDB.instanse(Blog.bdbName).getEntityStore().getPrimaryIndex(Integer.class, Tag.class);
	
	protected static SecondaryIndex<String, Integer, Tag> indexOnName = 
		BDB.instanse(Blog.bdbName).getEntityStore().getSecondaryIndex(primaryIndex, String.class, "name");
	
	protected static SecondaryIndex<String, Integer, Tag> indexOnSlug = 
		BDB.instanse(Blog.bdbName).getEntityStore().getSecondaryIndex(primaryIndex, String.class, "slug");
	
	public static List<Tag> getAll() {
		final List<Tag> all = new ArrayList<Tag>();
		BDB.traverse(
				primaryIndex.entities(), 
				new Function<Void, Tag>(){
					@Override
					public Void invoke(Tag env) {
						all.add(env);
						return null;
					}
				}
		);
		
		return all;
	}
	
	public static Tag getById(Integer id) {
		return primaryIndex.get(id);
	}
	
	public static Tag getByName(String name){
		return indexOnName.get(name);
	}
	
	public static Tag getBySlug(String slug){
		return indexOnSlug.get(slug);
	}
	
	public static Tag persist(Tag tag){
		return primaryIndex.put(tag);
	}
	
	public Tag() {
	}
	
	public Tag(String name, String slug) {
		this.name = name;
		this.slug = slug;
	}
	
	@PrimaryKey(sequence = "tag-id")
	public Integer id;
	
	@SecondaryKey(relate = Relationship.ONE_TO_ONE)
	public String name;
	
	@SecondaryKey(relate = Relationship.ONE_TO_ONE)
	public String slug;

}
